import {Component, OnInit} from '@angular/core';
import {
  FormGroup,
  FormBuilder
} from '@angular/forms';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';

import {I18NService} from '../../../core/i18n/i18n.service';
import {PopupService} from '../../../shared/popup/popup.service';
import { filter } from 'rxjs/operators';
import { HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse } from '@angular/common/http';
import { UploadXHRArgs } from 'ng-zorro-antd';
import { forkJoin } from 'rxjs';
import {QuestionService} from "../service/question.service";
@Component({
  styles: [],
  templateUrl: './question-insert.html'
})

export class QuestionInsertComponent implements OnInit {



  _loading = false;

  page = {
    pageNo: 1,
    pageSize: 10,
    total: 1
  };
  baseUrl = 'http://localhost:8082/ueditor/uploadQuestionFile';
  validateForm: FormGroup;
  uploading = false;
  fileList: UploadFile[] = [];

  constructor(
    private fb: FormBuilder,
    private i18nService: I18NService,
    private questionService: QuestionService,
    private popupService: PopupService,
    private http: HttpClient,
    private msg: NzMessageService
  ) {
    this.validateForm = this.fb.group({
      choiceFile: null,
      blankFile: null,
      judgeFile: null
    });
  }

  ngOnInit(): void {
  }


  beforeUpload = (file: UploadFile): boolean => {
    this.fileList = this.fileList.concat(file);
    return false;
  };

  handleUpload(): void {
    const formData = new FormData();
    // tslint:disable-next-line:no-any
    this.fileList.forEach((file: any) => {
      formData.append('files[]', file);
    });
    this.uploading = true;
    // You can use any AJAX library you like
    const req = new HttpRequest('POST', this.baseUrl, formData, {
      // reportProgress: true
    });
    this.http
      .request(req)
      .pipe(filter(e => e instanceof HttpResponse))
      .subscribe(
        () => {
          this.uploading = false;
          this.fileList = [];
          this.msg.success('upload successfully.');
        },
        () => {
          this.uploading = false;
          this.msg.error('upload failed.');
        }
      );
  }




  customReq = (item: UploadXHRArgs) => {
    // 构建一个 FormData 对象，用于存储文件或其他参数
    const formData = new FormData();
    // tslint:disable-next-line:no-any
    formData.append('file', item.file as any);
    formData.append('id', '1000');
    const req = new HttpRequest('POST', item.action!, formData, {
      reportProgress: true,
      withCredentials: true
    });
    // 始终返回一个 `Subscription` 对象，nz-upload 会在适当时机自动取消订阅
    return this.http.request(req).subscribe(
      (event: HttpEvent<{}>) => {
        if (event.type === HttpEventType.UploadProgress) {
          if (event.total! > 0) {
            // tslint:disable-next-line:no-any
            (event as any).percent = (event.loaded / event.total!) * 100;
          }
          // 处理上传进度条，必须指定 `percent` 属性来表示进度
          item.onProgress!(event, item.file!);
        } else if (event instanceof HttpResponse) {
          // 处理成功
          item.onSuccess!(event.body, item.file!, event);
        }
      },
      err => {
        // 处理失败
        item.onError!(err, item.file!);
      }
    );
  };

  // 一个简单的分片上传
  customBigReq = (item: UploadXHRArgs) => {
    const size = item.file.size;
    const chunkSize = parseInt(size / 3 + '', 10);
    const maxChunk = Math.ceil(size / chunkSize);
    const reqs = Array(maxChunk)
      .fill(0)
      .map((_: {}, index: number) => {
        const start = index * chunkSize;
        let end = start + chunkSize;
        if (size - end < 0) {
          end = size;
        }
        const formData = new FormData();
        formData.append('file', item.file.slice(start, end));
        formData.append('start', start.toString());
        formData.append('end', end.toString());
        formData.append('index', index.toString());
        const req = new HttpRequest('POST', item.action!, formData, {
          withCredentials: true
        });
        return this.http.request(req);
      });
    return forkJoin(...reqs).subscribe(
      () => {
        // 处理成功
        item.onSuccess!({}, item.file!, event);
      },
      err => {
        // 处理失败
        item.onError!(err, item.file!);
      }
    );
  };

}
